package com.fare.taluo.queue;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.dayatang.domain.Entity;
import com.fare.taluo.application.crawl.TaskQueueLogApplication;
import com.fare.taluo.application.crawl.crawlstatistics.FdcCrawlStatisticsApplication;
import com.fare.taluo.application.crawl.crawlstatistics.PersistentRecordeApplication;
import com.fare.taluo.core.domain.BaseEntity;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.vo.core.TaskRecordEntityVO;
import com.fare.taluo.vo.crawl.statistics.PersistentRecordeVO;

public class CreatePersistenceTask extends BaseEntity<CreatePersistenceTask> implements Entity{
	
	/**
	 * 
	 */
	protected final Logger log=Logger.getLogger(getClass());
	private static final long serialVersionUID = 1L;
	@Resource(name = "taskQueueLogApplication")
	private TaskQueueLogApplication taskQueueLogApplication;
	@Resource(name = "fdcCrawlStatisticsApplication")
	private FdcCrawlStatisticsApplication fdcCrawlStatisticsApplication;
	@Resource(name ="persistentRecordeApplication")
	private PersistentRecordeApplication persistentRecordeApplication;
	
	private String endflagDate;//结束日期
	private String date;//开始日期
	private int flag;//执行频率
	private Integer status=0;//识别码
	public void execute() throws Exception {
		List<PersistentRecordeVO> listVo= persistentRecordeApplication.findAll();
		PersistentRecordeVO vo=new PersistentRecordeVO();
		String endDate =null;
		Date nextGrabDate=null;
		if(listVo.size()>0){
			vo=listVo.get(0);
			if(status==1){
				endflagDate+=":00";
				nextGrabDate=(DateUtils.StringToDate("yyyy-MM-dd HH:mm:ss",endflagDate));
			}else{
				nextGrabDate=vo.getNextGrabDate();
			}
			
		}
		StringBuffer logS=new StringBuffer();
		if(date ==null || date.equals("")){
			if(vo !=null && vo.getNextGrabDateStr() !=null && !vo.getNextGrabDateStr().equals("")){
				if(date==null || date.equals("")){
					date=vo.getNextGrabDateStr()+" 00:00:00";//当前要执行的任务日期
				}else{
					date+=":00";
				}
			}else{
				date=com.fare.taluo.util.DateUtils.getDateAfters(-1,"yyyy-MM-dd HH:mm:ss");//当前日期前一天
			}
		}else{
			date+=":00";
		}
		Date nowaday=new Date();
		//处理数据时按小时来处理
		int allDeals=0;
		if(DateUtils.compareDateByDate2( DateUtils.StringToDate("yyyy-MM-dd", DateUtils.nowyyyyMMdd()),nextGrabDate)){
			if(endflagDate==null || endflagDate.equals("")){
				endflagDate=DateUtils.getDateTimeAfter(date,24);
			}else{
				endflagDate+=":00";
			}
			if(flag<=0 ){
				if( vo.getFrequency()<=0 ){
					flag=6;
				}else{
					flag=vo.getFrequency();
				}
			}
			endDate=DateUtils.getDateTimeAfter(date,flag);
			Date thisDoGrabDate=DateUtils.StringToDate("yyyy-MM-dd", date);
			List<TaskRecordEntityVO> ListVo=null;
			int i=0;
			int n=0;
			while (n<2 && DateUtils.compareDateByDate(DateUtils.StringToDate("yyyy-MM-dd HH:mm", endflagDate),DateUtils.StringToDate("yyyy-MM-dd HH:mm", endDate))) {
				if(DateUtils.StringToDate("yyyy-MM-dd HH:mm", endflagDate).getTime()==DateUtils.StringToDate("yyyy-MM-dd HH:mm", endDate).getTime()){
					n++;
				}
				ListVo=new ArrayList<TaskRecordEntityVO>();
				i++;
				// 取log的数据，此数据为持久化的数据
				Calendar c1 = Calendar.getInstance(); 
				Calendar c2 = Calendar.getInstance();
				c1.setTime(DateUtils.StringToDate("yyyy-MM-dd HH:mm:ss", date));
				c2.setTime(DateUtils.StringToDate("yyyy-MM-dd HH:mm:ss", endDate));
				c1.add(Calendar.SECOND, 0);
				c2.add(Calendar.SECOND, -1);
				Date dateSeconde = c1.getTime(); 
				Date endDateSeconde = c2.getTime(); 
				
				String dates=DateUtils.dateToStr(dateSeconde, "yyyy-MM-dd HH:mm:ss");
				String endDates=DateUtils.dateToStr(endDateSeconde, "yyyy-MM-dd HH:mm:ss");
				ListVo = taskQueueLogApplication.getAllDatasByGrabDate(dates,endDates);
				System.out.println(i+"次"+dates+"   "+endDates+"  "+ListVo.size()+"条数据,"+flag);
					// 持久化数据入库
					try {
						fdcCrawlStatisticsApplication.saveDatas(ListVo);
						fdcCrawlStatisticsApplication.saveDatasForGrabDate(ListVo);
						fdcCrawlStatisticsApplication.saveDatasForFlightLine(ListVo);
						allDeals+=ListVo.size();
					} catch (Exception e) {
						e.printStackTrace();
						logS.append(e.getMessage());
					}
				logS.append("第"+i+"次,执行日期：从"+dates+"到 "+endDates+"完成数据：" + ListVo.size() + "条   ");
				endDate=DateUtils.getDateTimeAfter(endDate,flag);
				if(DateUtils.compareDateByDate(DateUtils.StringToDate("yyyy-MM-dd HH:mm", endDate),DateUtils.StringToDate("yyyy-MM-dd HH:mm", endflagDate))){
					n++;
					endDate=DateUtils.dateToStr(DateUtils.StringToDate("yyyy-MM-dd HH:mm:ss", endflagDate), "yyyy-MM-dd HH:mm:ss");
				}
				date=DateUtils.getDateTimeAfter(date,flag);
				
				//开始插入LOG
				Date addNextGrabDate=null,nextDoOpraTime=null;
				String nextGrabDateStr=null;
				if(vo.getNextTime()==null || status==0){
					nextDoOpraTime=DateUtils.StringToDate("yyyy-MM-dd HH:mm:ss",DateUtils.formatFutureDay(nowaday,"yyyy-MM-dd HH:mm:ss",1));
				}else{
					nextDoOpraTime=vo.getNextTime();
				}
				if(vo.getNextGrabDate() ==null){
					addNextGrabDate=new Date();
				}else if(status==1){
					nextGrabDateStr=com.fare.taluo.util.DateUtils.dateToStr(vo.getNextGrabDate(),"yyyy-MM-dd");
				}else{
					addNextGrabDate=vo.getNextGrabDate();
					nextGrabDateStr=com.fare.taluo.util.DateUtils.formatFutureDay(addNextGrabDate,"yyyy-MM-dd",1);
				}
				
				PersistentRecordeVO saveVo=new PersistentRecordeVO();
				PersistentRecordeVO updateVo=new PersistentRecordeVO();
				Date endOpration =new Date();
				//当前抓取日期下
				List<PersistentRecordeVO> logList= persistentRecordeApplication.findByGrabDate(DateUtils.dateToStr(thisDoGrabDate, "yyyy-MM-dd"));
				
				if(logList.size()==0){
					saveVo.setNextGrabDate(DateUtils.StringToDate("yyyy-MM-dd",nextGrabDateStr));
					saveVo.setCreateTime(nowaday);
					saveVo.setStartTime(nowaday);
					saveVo.setNextTime(nextDoOpraTime);
					saveVo.setEndTime(endOpration);
					saveVo.setThisGrabDate(thisDoGrabDate);
					saveVo.setStatus(status);
					if(n<2){
						saveVo.setTaskLog(logS.toString());
					}else{
						saveVo.setTaskLog(logS.append("总数据="+allDeals+"条").toString());
					}
					saveVo.setFrequency(flag);
					persistentRecordeApplication.saveOrUpdate(saveVo);
				}else{
					updateVo.setId(logList.get(0).getId());
					if(n<2){
						updateVo.setTaskLog(logS.toString());
					}else{
						updateVo.setTaskLog(logS.append("总数据="+allDeals+"条").toString());
					}
					updateVo.setCreateTime(nowaday);
					updateVo.setEndTime(endOpration);
					updateVo.setStartTime(logList.get(0).getStartTime());
					updateVo.setNextGrabDate(logList.get(0).getNextGrabDate());
					updateVo.setNextTime(logList.get(0).getNextTime());
					updateVo.setThisGrabDate(logList.get(0).getThisGrabDate());
					updateVo.setFrequency(logList.get(0).getFrequency());
					updateVo.setId(logList.get(0).getId());
					updateVo.setStatus(status);
					persistentRecordeApplication.saveOrUpdate(updateVo);
				}
				
			}
			
		}
		
	}
	
	@Override
	public Serializable getId() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isNew() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean existed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean notExisted() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean existed(String propertyName, Object propertyValue) {
		// TODO Auto-generated method stub
		return false;
	}

	public Logger getLog() {
		return log;
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}
	public String getEndflagDate() {
		return endflagDate;
	}
	public void setEndflagDate(String endflagDate) {
		this.endflagDate = endflagDate;
	}

	public Integer getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}
	

}
